package com.renfei.cameralibrary.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.cgfay.uitls.utils.DensityUtils;
import com.renfei.cameralibrary.R;

public class CircleProgressBar extends View {


    private static final String TAG = CircleProgressBar.class.getSimpleName();
    // 录制时的环形进度条
    private Paint mRecordPaint;
    // 录制时点击的圆形按钮
    private Paint mBgPaint;
    // 画笔宽度
    private int mStrokeWidth;
    // 圆形按钮半径
    private int mRadius;
    //控件宽度
    private int mWidth;
    //控件高度
    private int mHeight;
    // 圆的外接圆
    private RectF mRectF;
    //progress max value
    private int mMaxValue = 15;
    //per progress value
    private int mProgressValue;
    //是否开始record
    private boolean mIsStartRecord = false;
    //Arc left、top value
    private int mArcValue;
    //录制 time
    private long mRecordTime;

    private int MIN_RECORD_TIME = 500;

    // 是否允许录制
    private boolean mRecordEnable;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ++mProgressValue;
            postInvalidate();
            //当没有达到最大值时一直绘制
            if (mProgressValue <= mMaxValue) {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    public CircleProgressBar(Context context) {
        this(context, null);
    }

    public CircleProgressBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initParams(context);
    }

    public void setmMaxValue(int mMaxValue) {
        this.mMaxValue = mMaxValue;
    }

    //初始化画笔操作
    private void initParams(Context context) {
        mArcValue = mStrokeWidth = DensityUtils.dp2px(context, 3);


        mBgPaint = new Paint();
        mBgPaint.setAntiAlias(true);
        mBgPaint.setColor(context.getResources().getColor(R.color.white));
        mBgPaint.setStrokeWidth(mStrokeWidth);
        mBgPaint.setStyle(Paint.Style.FILL);

        mRecordPaint = new Paint();
        mRecordPaint.setAntiAlias(true);
        mRecordPaint.setColor(context.getResources().getColor(R.color.springgreen));
        mRecordPaint.setStrokeWidth(mStrokeWidth);
        mRecordPaint.setStyle(Paint.Style.STROKE);
        mRecordPaint.setTextSize(DensityUtils.sp2px(context, 30));

        mRadius = DensityUtils.dp2px(context, 30);


        mRectF = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mWidth = getWidth();
        mHeight = getHeight();
        if (mWidth != mHeight) {
            int min = Math.min(mWidth, mHeight);
            mWidth = min;
            mHeight = min;
        }

        if (mIsStartRecord) {

            canvas.drawCircle(mWidth / 2, mHeight / 2, (float) (mRadius * 1.2), mBgPaint);

            if (mProgressValue <= mMaxValue) {
                //left--->距Y轴的距离
                //top--->距X轴的距离
                //right--->距Y轴的距离
                //bottom--->距X轴的距离
                mRectF.left = mArcValue;
                mRectF.top = mArcValue;
                mRectF.right = mWidth - mArcValue;
                mRectF.bottom = mHeight - mArcValue;
                canvas.drawArc(mRectF, -90, ((float) mProgressValue / mMaxValue) * 360, false, mRecordPaint);

                /**
                 * 绘制文字
                 */
                String textVaule = String.valueOf(mMaxValue - mProgressValue);

                float textWidth = mRecordPaint.measureText(textVaule);
                // 将坐标原点移到控件中心
                canvas.translate(getWidth() / 2, getHeight() / 2); // 将坐标原点移到控件中心
                // 文字baseline在y轴方向的位置
                float baseLineY = Math.abs(mRecordPaint.ascent() + mRecordPaint.descent()) / 2;
                canvas.drawText(textVaule, -textWidth / 2, baseLineY, mRecordPaint);


                if (mProgressValue == mMaxValue) {
                    mProgressValue = 0;
                    mHandler.removeMessages(0);
                    mIsStartRecord = false;
                    //这里可以回调出去表示已到录制时间最大值
                    //code.....
                    if (null != recordButtonListener) {
                        recordButtonListener.onRecordFinish();
                    }
                }
            }
        } else {
            canvas.drawCircle(mWidth / 2, mHeight / 2, mRadius, mBgPaint);
        }
    }

    //重新该方法来完成触摸时，圆变大的效果
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mRecordEnable) {
            return super.onTouchEvent(event);
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mIsStartRecord = true;
                mRecordTime = System.currentTimeMillis();
                mHandler.sendEmptyMessage(0);
                //这里可以回调出去表示已经开始录制了
                //code.....
                if (null != recordButtonListener) {
                    recordButtonListener.onRecordStart();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mRecordTime > 0) {
                    //录制的时间（单位：秒）
                    int actualRecordTime = (int) ((System.currentTimeMillis() - mRecordTime) / 1000);
                    //这里回调出去表示已经取消录制了
                    //code.....
                    if (actualRecordTime < MIN_RECORD_TIME) {
                        if (null != recordButtonListener) {
                            recordButtonListener.onRecordCancel();
                        }
                    } else {
                        if (null != recordButtonListener) {
                            recordButtonListener.onRecordFinish();
                        }
                    }
                }
                mHandler.removeMessages(0);
                mIsStartRecord = false;
                mRecordTime = 0;
                mProgressValue = 0;
                postInvalidate();
                break;
            case MotionEvent.ACTION_CANCEL:
                //这里可以回调出去表示已经取消录制了
                //code.....
                if (null != recordButtonListener) {
                    recordButtonListener.onRecordCancel();
                }
                mHandler.removeMessages(0);
                mIsStartRecord = false;
                mRecordTime = 0;
                mProgressValue = 0;
                postInvalidate();
                break;
        }

        return true;
    }


    /**
     * 设置是否允许录制
     *
     * @param enable false时，为点击拍照
     */
    public void setRecordEnable(boolean enable) {
        mRecordEnable = enable;
    }


    private RecordButtonListener recordButtonListener;

    public void setRecordButtonListener(RecordButtonListener recordButtonListener) {
        this.recordButtonListener = recordButtonListener;
    }

    public interface RecordButtonListener {
        void onRecordStart();

        void onRecordCancel();

        void onRecordFinish();
    }

}
